package com.sxhuayuan.parking.compenent.shiro;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;

import com.sxhuayuan.parking.compenent.shiro.realm.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sxhuayuan.parking.compenent.shiro.filter.MyFormAuthenticationFilter;
import com.sxhuayuan.parking.service.LogService;

import net.sf.ehcache.CacheManager;

@Configuration
public class ShiroConfigureBeans {

	Logger log = LoggerFactory.getLogger(getClass());

	@Bean
	public ModularRealmAuthenticator modularRealmAuthenticator() {
		log.debug("自定义modularRealmAuthenticator");
		MyModularRealmAuthenticator modularRealmAuthenticator = new MyModularRealmAuthenticator();
		modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
		return modularRealmAuthenticator;
	}

	@Bean("shiroEhCacheManager")
	public EhCacheManager shiroEhCacheManager(CacheManager cacheManager) {
		EhCacheManager bean = new EhCacheManager();
		bean.setCacheManager(cacheManager);
		return bean;
	}

	@Bean
	@ConfigurationProperties(prefix = "spring.redis")
	public RedisManager redisManager() {
		log.debug("创建自定义shiro.RedisManager");
		return new RedisManager();
	}

	@Bean
	public SessionDAO sessionDAO() {
		RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
		redisSessionDAO.setExpire(3600);
		redisSessionDAO.setRedisManager(redisManager());
		return redisSessionDAO;
	}

	@Bean("defaultSessionManager")
	public DefaultWebSessionManager sessionManager() {
		DefaultWebSessionManager manager = new MySessionManager();
		manager.setSessionDAO(sessionDAO());
		manager.setSessionIdCookie(sessionIdCookie());
		manager.setGlobalSessionTimeout(3600 * 1000);
		manager.setSessionValidationInterval(120 * 1000);
		manager.setSessionValidationSchedulerEnabled(true);
		// 取消url 后面的 JSESSIONID
		manager.setSessionIdUrlRewritingEnabled(false);
		return manager;
	}

	@Bean("securityManager")
	public DefaultWebSecurityManager securityManager(@Qualifier("shiroEhCacheManager") EhCacheManager cacheManager, AdminAuthenticationRealm adminRealm, AgentAuthenticationRealm agentRealm,
			MemberAuthenticationRealm memberRealm, ParkingLotAuthenticationRealm ParkingLotRealm, SalesmanAuthenticationRealm salesmanRealm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setCacheManager(cacheManager);
		securityManager.setSessionManager(sessionManager());
		// 自定义认证器，用来路由不同类型用户登录时的realm
		securityManager.setAuthenticator(modularRealmAuthenticator());
		List<Realm> realms = new ArrayList<>();
		realms.add(adminRealm);
		realms.add(agentRealm);
		realms.add(memberRealm);
		realms.add(ParkingLotRealm);
		realms.add(salesmanRealm);
		securityManager.setRealms(realms);
		return securityManager;
	}

	/**
	 * 配置保存sessionId的cookie 注意：这里的cookie 不是上面的记住我 cookie 记住我需要一个cookie session管理
	 * 也需要自己的cookie
	 * 
	 * @return
	 */
	@Bean("sessionIdCookie")
	public SimpleCookie sessionIdCookie() {
		// 这个参数是cookie的名称
		SimpleCookie simpleCookie = new SimpleCookie(MySessionManager.TOKEN_KEY);
		// setcookie的httponly属性如果设为true的话，会增加对xss防护的安全系数。它有以下特点：

		// setcookie()的第七个参数
		// 设为true后，只能通过http访问，javascript无法访问
		// 防止xss读取cookie
		simpleCookie.setHttpOnly(true);
		simpleCookie.setPath("/");
		// maxAge=-1表示浏览器关闭时失效此Cookie
		simpleCookie.setMaxAge(-1);
		return simpleCookie;
	}

	// @Bean
	public MyFormAuthenticationFilter authenticationFilter() {
		MyFormAuthenticationFilter filter = new MyFormAuthenticationFilter();
		return filter;
	}

	@Bean
	public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager, LogService logService) {
		SecurityUtils.setSecurityManager(securityManager); // 设置到当前环境中

		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		HashMap<String, Filter> filters = new HashMap<>();
		MyFormAuthenticationFilter myFormAuthenticationFilter = new MyFormAuthenticationFilter();
		myFormAuthenticationFilter.setLogService(logService);
		filters.put("authc", myFormAuthenticationFilter);
		shiroFilterFactoryBean.setFilters(filters);

		shiroFilterFactoryBean.setSecurityManager(securityManager);

		Map<String, String> filterChain = new LinkedHashMap<>();
		filterChain.put("/common/**", "anon");
		filterChain.put("/*/login", "authc");
		filterChain.put("/admin/**", "authc");
		filterChain.put("/agent/**", "authc");
		filterChain.put("/**", "anon");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChain); // 添加过滤器
		shiroFilterFactoryBean.setLoginUrl("/*/login");// 验证失败 走login
		return shiroFilterFactoryBean;
	}

	@Bean
	public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}

	@Bean
	public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
		DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
		creator.setProxyTargetClass(true);
		return creator;
	}

	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
		AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
		advisor.setSecurityManager(manager);
		return advisor;
	}

}
